package com.aurifa.struts2.tutorial.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;

import com.aurifa.struts2.tutorial.model.Department;

public class DepartmentMySqldao implements DepartmentDao {
	private static List departments;
	private static Map departmentsMap;
	static {
		departments = new ArrayList();
		Connection con = null;
		Statement s = null;
		ResultSet rs = null;
		try {
			con = MySqldao.getCon();
			s = con.createStatement();
			rs = s.executeQuery("select * from department");
			while (rs.next()) {
				departments.add(new Department(rs.getInt(1), rs.getString(2)));
			}
			try {
				if (rs != null)
					rs.close();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null)
					rs.close();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			try {
				if (s != null)
					s.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if (con != null)
					con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		departmentsMap = new HashMap();
		Iterator iter = departments.iterator();
		while (iter.hasNext()) {
			Department dept = (Department) iter.next();
			departmentsMap.put(dept.getDepartmentId(), dept);
		}
	}

	public List getAllDepartments() {
		return departments;
	}

	public Map getDepartmentsMap() {
		return departmentsMap;
	}
}
